<?php
/**
 *  * *    author 韩天尊
 * *    Date: 2022/4/1
 * *    Email: <724700483@qq.com>
 */

namespace App\Toolys\VerifyCode;

use App\Toolys\CustomHttpException;
use EasySwoole\Http\Message\Status;
use EasySwoole\Utility\Random;
use EasySwoole\VerifyCode\Conf;

class VerifyCode
{
    static $VERIFY_CODE_TTL = 180;
    static $VERIFY_CODE_LENGTH = 4;

    // 生成验证码
    public function verifyCode(string $event, \EasySwoole\Http\Response $response)
    {
        // 配置验证码
        $config = new Conf();
        $code = new \EasySwoole\VerifyCode\VerifyCode($config);

        // 获取随机数(即验证码的具体值)
        $random = Random::character(self::$VERIFY_CODE_LENGTH, '1234567890abcdefghijklmnopqrstuvwxyz');
        // var_dump($random);    string(4) "m02t"

        // 绘制验证码
        $code = $code->DrawCode($random);

        // 获取验证码的 base64 编码及设置验证码有效时间
        $time = time();

        // 将验证码加密存储在 Cookie 中，方便进行后续验证。用户也可以把验证码保存在 Session 或者 Redis中，方便后续验证。
        $response->setCookie("verifyCodeHash", VerifyCodeTools::getVerifyCodeHash($event.$random, $time), $time + self::$VERIFY_CODE_TTL, '/');
        $response->setCookie('verifyCodeTime', $time, $time + self::$VERIFY_CODE_TTL, '/');

        // 设置响应文件内容类型
        $response->withHeader('Content-Type','image/png');
        // 向客户端输出验证码图片
        $response->write($code->getImageByte());
    }

    // 校验验证码

    /**
     * @throws CustomHttpException
     */
    public function checkVerifyCode(string $event, $code, \EasySwoole\Http\Request $request)
    {
        $verifyCodeHash = $request->getCookieParams('verifyCodeHash');
        $verifyCodeTime = $request->getCookieParams('verifyCodeTime');
        if (!VerifyCodeTools::checkVerifyCode($event.$code, $verifyCodeTime, $verifyCodeHash)) {
            $customHttpException = new CustomHttpException();
            $customHttpException->setCode(400)->setMessage("验证码错误");
            throw $customHttpException;
        }
    }
}